package proxy4jdbc3.jdbc;

import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.SQLException;

import javax.sql.DataSource;

import proxy4jdbc3.JDBCProxy;
import proxy4jdbc3.JDBCReporter;

/**
 * Extends this to make your DataSourceProxy solution 
 * @author fabricio.epaminondas
 *
 */
public abstract class DataSourceProxy implements DataSource, JDBCProxy<DataSource> {

	private DataSource realDataSource;
	
	/**
	 * Constructs the DataSourceProxy  and call method
	 * <code> newDriverInstance();</code> 
	 * 
	 */
	public DataSourceProxy() {
		try {
			this.realDataSource = newDataSourceInstance();

			if (this.realDataSource == null)
				throw new Exception("DataSource instance could not be null!");

		} catch (Exception s) {
			throw (RuntimeException) new RuntimeException(
					"Could not recover the instance of DataSource!")
					.initCause(s);
		}
	}
	
	/**
	 * Factory method to create the Data Source instance.
	 * @return instance
	 * @throws InstantiationException
	 * @throws IllegalAccessException
	 * @throws ClassNotFoundException
	 */
	public abstract DataSource newDataSourceInstance() throws InstantiationException,
	IllegalAccessException, ClassNotFoundException;

	/**
	 * The observer of proxified jdbc object
	 * @return the reporter
	 */
	public abstract JDBCReporter getReporter();

	public DataSource getProxyfied() {
		return realDataSource;
	}

	public Connection getConnection() throws SQLException {
		return  new ConnectionProxy(getReporter(), getProxyfied().getConnection());
	}

	public Connection getConnection(String username, String password)
			throws SQLException {
		return new ConnectionProxy(getReporter(), getProxyfied().getConnection(username, password));
	}

	public PrintWriter getLogWriter() throws SQLException {
		return getProxyfied().getLogWriter();
	}

	public int getLoginTimeout() throws SQLException {
		return getProxyfied().getLoginTimeout();
	}

	public void setLogWriter(PrintWriter out) throws SQLException {
		getProxyfied().setLogWriter(out);

	}

	public void setLoginTimeout(int seconds) throws SQLException {
		getProxyfied().setLoginTimeout(seconds);
	}


}